<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>贪吃蛇·手机版</title>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
<style>
  *{margin:0;padding:0;box-sizing:border-box}
  body{
    background: linear-gradient(135deg, #0d0d0d 0%, #1a1a2e 50%, #16213e 100%);
    display:flex;
    flex-direction:column;
    align-items:center;
    font-family:Arial;
    color:#eee;
    height:100vh;
    overflow:hidden;
    position:relative;
    touch-action: none;
  }
  body::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: 
      radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.1) 0%, transparent 50%),
      radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.08) 0%, transparent 50%),
      radial-gradient(circle at 40% 40%, rgba(120, 219, 255, 0.05) 0%, transparent 50%);
    pointer-events: none;
    z-index: -1;
  }
  
  /* 开始界面 */
  #startScreen {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.9);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 100;
    backdrop-filter: blur(10px);
    padding: 20px;
  }
  
  .game-title {
    font-size: 48px;
    margin-bottom: 40px;
    color: #ffd700;
    text-shadow: 0 0 20px #ffd700;
    text-align: center;
  }
  
  .input-group {
    margin: 20px 0;
    text-align: center;
  }
  
  .input-group label {
    display: block;
    margin-bottom: 10px;
    font-size: 18px;
    color: #fff;
  }
  
  .player-input {
    padding: 12px 20px;
    font-size: 18px;
    border: 2px solid #444;
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.1);
    color: #fff;
    text-align: center;
    width: 250px;
    max-width: 90vw;
  }
  
  .player-input:focus {
    outline: none;
    border-color: #ffd700;
  }
  
  .difficulty-selector {
    display: flex;
    gap: 15px;
    margin: 20px 0;
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .difficulty-btn {
    padding: 15px 30px;
    font-size: 18px;
    border: 2px solid #444;
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.1);
    color: #fff;
    cursor: pointer;
    transition: all 0.3s;
    min-width: 120px;
  }
  
  .difficulty-btn.active {
    background: linear-gradient(45deg, #ffd700, #ffed4e);
    color: #111;
    border-color: #ffd700;
    box-shadow: 0 0 20px rgba(255, 215, 0, 0.3);
  }
  
  .difficulty-btn:hover {
    transform: translateY(-2px);
  }
  
  .control-mode {
    display: flex;
    gap: 10px;
    margin: 15px 0;
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .control-btn {
    padding: 10px 20px;
    font-size: 14px;
    border: 1px solid #444;
    border-radius: 6px;
    background: rgba(255, 255, 255, 0.1);
    color: #fff;
    cursor: pointer;
    transition: all 0.3s;
  }
  
  .control-btn.active {
    background: rgba(0, 170, 255, 0.3);
    border-color: #00aaff;
  }
  
  .start-btn {
    padding: 15px 50px;
    font-size: 20px;
    border: none;
    border-radius: 8px;
    background: linear-gradient(45deg, #00aaff, #0088cc);
    color: #fff;
    cursor: pointer;
    margin-top: 30px;
    transition: all 0.3s;
    font-weight: bold;
  }
  
  .start-btn:hover {
    transform: scale(1.05);
    box-shadow: 0 0 30px rgba(0, 170, 255, 0.5);
  }
  
  #scoreBoard{
    width:100%;
    display:flex;
    align-items:center;
    justify-content:space-between;
    padding:10px 15px;
    font-size:18px;
    flex-wrap:wrap;
    gap:10px;
    background: rgba(0, 0, 0, 0.3);
    backdrop-filter: blur(10px);
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    z-index: 1;
  }
  
  .game-container {
    position: relative;
    margin: auto;
    padding: 10px;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 15px;
    box-shadow: 
      0 0 50px rgba(0, 170, 255, 0.1),
      inset 0 0 50px rgba(0, 0, 0, 0.3);
    max-width: 95vw;
    max-height: 60vh;
  }
  
  canvas{
    background:#111;
    border: 2px solid rgba(51, 51, 51, 0.8);
    box-shadow: 
      0 0 30px rgba(0, 170, 255, 0.2),
      inset 0 0 30px rgba(0, 0, 0, 0.5);
    border-radius: 8px;
    display: block;
    max-width: 100%;
    max-height: 100%;
  }
  
  #gameOver{
    display:none;
    text-align:center;
    margin-top:15px;
    font-size:20px;
    background: rgba(0, 0, 0, 0.8);
    padding: 20px;
    border-radius: 10px;
    backdrop-filter: blur(10px);
    max-width: 90vw;
  }
  
  .game-over-buttons {
    display: flex;
    gap: 15px;
    justify-content: center;
    margin-top: 20px;
    flex-wrap: wrap;
  }
  
  .game-over-btn {
    padding: 12px 25px;
    font-size: 16px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s;
    font-weight: bold;
  }
  
  .restart-btn {
    background: linear-gradient(45deg, #ffd700, #ffed4e);
    color: #111;
  }
  
  .ranking-btn {
    background: linear-gradient(45deg, #00aaff, #0088cc);
    color: #fff;
  }
  
  .menu-btn {
    background: rgba(255, 255, 255, 0.1);
    color: #fff;
    border: 1px solid #444;
  }
  
  .game-over-btn:hover {
    transform: scale(1.05);
  }
  
  #levelTransition{
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background:rgba(0,0,0,0.9);
    display:none;
    justify-content:center;
    align-items:center;
    flex-direction:column;
    z-index:30;
    font-size:24px;
    text-align:center;
    backdrop-filter: blur(20px);
  }
  
  #transitionText{
    margin-bottom:30px;
    color: #fff;
    text-shadow: 0 0 20px #ffd700;
  }
  
  #countdown{
    font-size:72px;
    color:#ffd700;
    font-weight:bold;
    text-shadow: 0 0 30px #ffd700;
    animation: pulse 1s infinite;
  }
  
  @keyframes pulse {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.1); }
  }

  /* 虚拟方向键 */
  #virtualController {
    position: fixed;
    bottom: 30px;
    right: 30px;
    width: 150px;
    height: 150px;
    z-index: 10;
    display: none;
  }
  
  .dpad {
    position: relative;
    width: 100%;
    height: 100%;
  }
  
  .direction-btn {
    position: absolute;
    width: 50px;
    height: 50px;
    background: rgba(255, 255, 255, 0.2);
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: white;
    cursor: pointer;
    user-select: none;
    transition: all 0.2s;
    backdrop-filter: blur(10px);
  }
  
  .direction-btn:active {
    background: rgba(255, 215, 0, 0.4);
    transform: scale(0.9);
  }
  
  .direction-btn.up {
    top: 0;
    left: 50%;
    transform: translateX(-50%);
  }
  
  .direction-btn.down {
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
  }
  
  .direction-btn.left {
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }
  
  .direction-btn.right {
    right: 0;
    top: 50%;
    transform: translateY(-50%);
  }
  
  .direction-btn.center {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(255, 255, 255, 0.1);
    font-size: 20px;
  }

  /* 摇杆控制器 */
  #joystickContainer {
    position: fixed;
    bottom: 30px;
    right: 30px;
    width: 120px;
    height: 120px;
    z-index: 10;
    display: none;
  }
  
  .joystick-base {
    position: absolute;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.1);
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    backdrop-filter: blur(10px);
  }
  
  .joystick-handle {
    position: absolute;
    width: 50px;
    height: 50px;
    background: rgba(255, 215, 0, 0.6);
    border: 2px solid rgba(255, 255, 255, 0.5);
    border-radius: 50%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    transition: all 0.1s;
    box-shadow: 0 0 15px rgba(255, 215, 0, 0.4);
  }
  
  .joystick-handle.active {
    background: rgba(255, 215, 0, 0.8);
    box-shadow: 0 0 25px rgba(255, 215, 0, 0.6);
  }
  
  /* 方向指示器 */
  .direction-indicators {
    position: absolute;
    width: 100%;
    height: 100%;
    pointer-events: none;
  }
  
  .direction-indicator {
    position: absolute;
    width: 20px;
    height: 20px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    transform: translate(-50%, -50%);
  }
  
  .direction-indicator.up {
    top: 15%;
    left: 50%;
  }
  
  .direction-indicator.down {
    bottom: 15%;
    left: 50%;
    top: auto;
  }
  
  .direction-indicator.left {
    left: 15%;
    top: 50%;
  }
  
  .direction-indicator.right {
    right: 15%;
    top: 50%;
    left: auto;
  }

  /* 手势控制区域 */
  #gestureArea {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 5;
    display: none;
  }

  /* 排行榜 */
  #rankingScreen {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.95);
    display: none;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 100;
    backdrop-filter: blur(10px);
    padding: 20px;
  }
  
  .ranking-title {
    font-size: 36px;
    margin-bottom: 30px;
    color: #ffd700;
    text-shadow: 0 0 20px #ffd700;
  }
  
  .ranking-list {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 10px;
    padding: 20px;
    max-height: 400px;
    overflow-y: auto;
    margin-bottom: 30px;
    min-width: 300px;
    max-width: 90vw;
  }
  
  .ranking-item {
    display: flex;
    justify-content: space-between;
    padding: 10px 15px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  }
  
  .ranking-item:last-child {
    border-bottom: none;
  }
  
  .ranking-item.current {
    background: rgba(255, 215, 0, 0.2);
    border-radius: 5px;
  }
  
  .player-name {
    color: #fff;
  }
  
  .player-score {
    color: #ffd700;
    font-weight: bold;
  }
  
  .ranking-buttons {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .ranking-btn {
    padding: 12px 25px;
    font-size: 16px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s;
  }
  
  .play-again {
    background: linear-gradient(45deg, #00aaff, #0088cc);
    color: #fff;
  }
  
  .back-to-menu {
    background: rgba(255, 255, 255, 0.1);
    color: #fff;
    border: 1px solid #444;
  }
  
  .ranking-btn:hover {
    transform: scale(1.05);
  }

  .difficulty-indicator {
    margin-left:10px;
    font-size:14px;
    color:#ffd700;
    font-weight: bold;
  }
  
  #foodGuide{
    position:fixed;
    bottom:20px;
    left:20px;
    background: rgba(34, 34, 34, 0.9);
    padding:12px 16px;
    border-radius:10px;
    font-size:12px;
    display:flex;
    gap:12px;
    flex-wrap:wrap;
    max-width:320px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }
  
  .food-item{
    display:flex;
    align-items:center;
    gap:6px;
  }
  
  .food-color{
    width:14px;
    height:14px;
    border-radius:50%;
    box-shadow: 0 0 8px currentColor;
  }

  /* 浮动粒子背景 */
  .floating-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: -1;
    overflow: hidden;
  }
  
  .floating-particle {
    position: absolute;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
    animation: float 20s infinite linear;
  }
  
  @keyframes float {
    0% {
      transform: translateY(100vh) rotate(0deg);
      opacity: 0;
    }
    10% {
      opacity: 0.3;
    }
    90% {
      opacity: 0.3;
    }
    100% {
      transform: translateY(-100px) rotate(360deg);
      opacity: 0;
    }
  }

  /* 网格背景 */
  .grid-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: 
      linear-gradient(rgba(255, 255, 255, 0.03) 1px, transparent 1px),
      linear-gradient(90deg, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
    background-size: 50px 50px;
    pointer-events: none;
    z-index: -1;
  }

  /* 霓虹文字效果 */
  .neon-text {
    text-shadow: 
      0 0 5px currentColor,
      0 0 10px currentColor,
      0 0 20px currentColor;
  }

  /* 手机优化 */
  @media (max-width: 768px) {
    .game-title {
      font-size: 36px;
      margin-bottom: 30px;
    }
    
    #scoreBoard {
      font-size: 16px;
      padding: 8px 12px;
    }
    
    .game-container {
      padding: 5px;
      max-height: 50vh;
    }
    
    #virtualController {
      bottom: 20px;
      right: 20px;
      width: 120px;
      height: 120px;
    }
    
    .direction-btn {
      width: 40px;
      height: 40px;
      font-size: 20px;
    }
    
    #joystickContainer {
      bottom: 20px;
      right: 20px;
      width: 100px;
      height: 100px;
    }
    
    .joystick-handle {
      width: 40px;
      height: 40px;
    }
    
    #foodGuide {
      bottom: 10px;
      left: 10px;
      padding: 8px 12px;
      font-size: 10px;
    }
  }
</style>
</head>
<body>
<!-- 背景元素 -->
<div class="grid-bg"></div>
<div class="floating-bg" id="floatingBg"></div>

<!-- 开始界面 -->
<div id="startScreen">
  <h1 class="game-title">🐍 贪吃蛇大冒险</h1>
  
  <div class="input-group">
    <label for="playerName">请输入玩家姓名：</label>
    <input type="text" id="playerName" class="player-input" placeholder="游客" maxlength="10">
  </div>
  
  <div class="input-group">
    <label>选择难度：</label>
    <div class="difficulty-selector">
      <button class="difficulty-btn active" data-difficulty="normal">一般</button>
      <button class="difficulty-btn" data-difficulty="hard">困难</button>
      <button class="difficulty-btn" data-difficulty="challenge">挑战</button>
    </div>
  </div>

  <div class="input-group">
    <label>控制方式：</label>
    <div class="control-mode">
      <button class="control-btn active" data-control="virtual">虚拟按键</button>
      <button class="control-btn" data-control="joystick">摇杆控制</button>
      <button class="control-btn" data-control="gesture">滑动手势</button>
    </div>
  </div>
  
  <button class="start-btn" onclick="startGame()">开始游戏</button>
</div>

<!-- 游戏界面 -->
<div id="gameScreen" style="display: none;">
  <div id="scoreBoard">
    <span>玩家：<span id="currentPlayer" style="color: #0af;">-</span></span>
    <span>得分：<span id="score" class="neon-text" style="color: #0af;">0</span></span>
    <span>积分：<span id="points" class="neon-text" style="color: #0af;">0</span></span>
    <span>历史最高：<span id="highScore" class="neon-text" style="color: #ffd700;">0</span></span>
    <span>关卡：<span id="level" class="neon-text" style="color: #0af;">1</span><span class="difficulty-indicator" id="difficultyText">一般</span></span>
  </div>

  <div class="game-container">
    <canvas id="canvas"></canvas>
  </div>

  <div id="gameOver">
    <div id="finalTxt">游戏结束！</div>
    <div>本次获得 <span id="finalPoints" style="color: #ffd700;">0</span> 积分</div>
    <div id="newRecord">🎉 新纪录诞生！</div>
    <div class="game-over-buttons">
      <button class="game-over-btn restart-btn" onclick="restartGame()">重新开始</button>
      <button class="game-over-btn ranking-btn" onclick="showRanking()">查看排行榜</button>
      <button class="game-over-btn menu-btn" onclick="backToMenu()">返回菜单</button>
    </div>
  </div>

  <div id="levelTransition">
    <div id="transitionText">准备进入第 <span id="nextLevelNum" style="color: #ffd700;">2</span> 关</div>
    <div id="countdown">3</div>
  </div>

  <!-- 虚拟方向键 -->
  <div id="virtualController">
    <div class="dpad">
      <div class="direction-btn up" data-direction="up">↑</div>
      <div class="direction-btn down" data-direction="down">↓</div>
      <div class="direction-btn left" data-direction="left">←</div>
      <div class="direction-btn right" data-direction="right">→</div>
      <div class="direction-btn center">控制</div>
    </div>
  </div>

  <!-- 摇杆控制器 -->
  <div id="joystickContainer">
    <div class="joystick-base"></div>
    <div class="direction-indicators">
      <div class="direction-indicator up"></div>
      <div class="direction-indicator down"></div>
      <div class="direction-indicator left"></div>
      <div class="direction-indicator right"></div>
    </div>
    <div class="joystick-handle" id="joystickHandle"></div>
  </div>

  <!-- 手势控制区域 -->
  <div id="gestureArea"></div>

  <div id="foodGuide">
    <div class="food-item"><div class="food-color" style="background:#0af;"></div>苹果(+1)</div>
    <div class="food-item"><div class="food-color" style="background:#ff4081;"></div>草莓(+2)</div>
    <div class="food-item"><div class="food-color" style="background:#ffd700;"></div>蛋糕(+5)</div>
    <div class="food-item"><div class="food-color" style="background:#ff4444;"></div>炸弹(死亡)</div>
  </div>
</div>

<!-- 排行榜界面 -->
<div id="rankingScreen">
  <h2 class="ranking-title">🏆 排行榜</h2>
  <div class="ranking-list" id="rankingList">
    <!-- 排行榜内容将通过JavaScript动态生成 -->
  </div>
  <div class="ranking-buttons">
    <button class="ranking-btn play-again" onclick="playAgain()">再玩一次</button>
    <button class="ranking-btn back-to-menu" onclick="backToMenu()">返回菜单</button>
  </div>
</div>

<script>
// 难度配置
const DIFFICULTY_CONFIG = {
  normal: {
    name: "一般",
    speed: 120,
    bombRate: 0.05,
    maxBombs: 1
  },
  hard: {
    name: "困难", 
    speed: 90,
    bombRate: 0.08,
    maxBombs: 2
  },
  challenge: {
    name: "挑战",
    speed: 70,
    bombRate: 0.12,
    maxBombs: 2
  }
};

// 控制模式
let currentControlMode = 'virtual';

// 游戏状态变量
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let W, H;

let snake, dir, score, particles, foods, lastMove, baseSpeed;
let totalPoints = 0;
let currentPlayer = '';
let highScore = localStorage.getItem('snakeHighScore') || 0;
let currentLevel = 0;
let isLevelTransitioning = false;
let transitionCountdown = 3;
let gameLoopId = null;

// 摇杆相关变量
let isJoystickActive = false;
let joystickBaseX = 0;
let joystickBaseY = 0;
let joystickBaseRadius = 0;
let currentJoystickDirection = null;

// 初始化背景
function initBackground() {
  const floatingBg = document.getElementById('floatingBg');
  const particleCount = 15;
  
  for (let i = 0; i < particleCount; i++) {
    const particle = document.createElement('div');
    particle.className = 'floating-particle';
    
    const size = Math.random() * 4 + 1;
    particle.style.width = `${size}px`;
    particle.style.height = `${size}px`;
    
    const colors = [
      'rgba(0, 170, 255, 0.3)',
      'rgba(255, 215, 0, 0.3)',
      'rgba(255, 64, 129, 0.3)',
      'rgba(100, 255, 218, 0.3)'
    ];
    particle.style.background = colors[Math.floor(Math.random() * colors.length)];
    
    particle.style.left = `${Math.random() * 100}%`;
    particle.style.animationDelay = `${Math.random() * 20}s`;
    particle.style.animationDuration = `${15 + Math.random() * 15}s`;
    
    floatingBg.appendChild(particle);
  }
}

initBackground();

// 难度选择
let currentDifficulty = 'normal';
document.querySelectorAll('.difficulty-btn').forEach(btn => {
  btn.addEventListener('click', function() {
    document.querySelectorAll('.difficulty-btn').forEach(b => b.classList.remove('active'));
    this.classList.add('active');
    currentDifficulty = this.dataset.difficulty;
  });
});

// 控制模式选择
document.querySelectorAll('.control-btn').forEach(btn => {
  btn.addEventListener('click', function() {
    document.querySelectorAll('.control-btn').forEach(b => b.classList.remove('active'));
    this.classList.add('active');
    currentControlMode = this.dataset.control;
  });
});

// 玩家姓名输入 - 设置默认值
document.getElementById('playerName').value = '游客';

// 开始游戏
function startGame() {
  let playerName = document.getElementById('playerName').value.trim();
  if (!playerName) {
    playerName = '游客';
  }
  
  document.getElementById('startScreen').style.display = 'none';
  document.getElementById('gameScreen').style.display = 'block';
  document.getElementById('currentPlayer').textContent = playerName;
  
  currentPlayer = playerName;
  
  // 根据控制模式显示相应的控制器
  if (currentControlMode === 'virtual') {
    document.getElementById('virtualController').style.display = 'block';
    document.getElementById('joystickContainer').style.display = 'none';
    document.getElementById('gestureArea').style.display = 'none';
  } else if (currentControlMode === 'joystick') {
    document.getElementById('virtualController').style.display = 'none';
    document.getElementById('joystickContainer').style.display = 'block';
    document.getElementById('gestureArea').style.display = 'none';
    setTimeout(setupJoystickControls, 100); // 延迟确保DOM已渲染
  } else {
    document.getElementById('virtualController').style.display = 'none';
    document.getElementById('joystickContainer').style.display = 'none';
    document.getElementById('gestureArea').style.display = 'block';
    setupGestureControls();
  }
  
  init();
}

// 设置摇杆控制
function setupJoystickControls() {
  const joystickContainer = document.getElementById('joystickContainer');
  const joystickHandle = document.getElementById('joystickHandle');
  
  // 获取摇杆基础位置和半径
  const rect = joystickContainer.getBoundingClientRect();
  joystickBaseX = rect.left + rect.width / 2;
  joystickBaseY = rect.top + rect.height / 2;
  joystickBaseRadius = rect.width / 2 - 25;
  
  let touchId = null;
  
  // 触摸开始
  joystickContainer.addEventListener('touchstart', function(e) {
    e.preventDefault();
    if (touchId === null) {
      const touch = e.touches[0];
      touchId = touch.identifier;
      isJoystickActive = true;
      joystickHandle.classList.add('active');
      updateJoystickPosition(touch.clientX, touch.clientY);
    }
  });
  
  // 触摸移动
  document.addEventListener('touchmove', function(e) {
    if (!isJoystickActive) return;
    
    e.preventDefault();
    
    for (let i = 0; i < e.changedTouches.length; i++) {
      const touch = e.changedTouches[i];
      if (touch.identifier === touchId) {
        updateJoystickPosition(touch.clientX, touch.clientY);
        break;
      }
    }
  }, { passive: false });
  
  // 触摸结束
  document.addEventListener('touchend', function(e) {
    if (!isJoystickActive) return;
    
    e.preventDefault();
    
    for (let i = 0; i < e.changedTouches.length; i++) {
      const touch = e.changedTouches[i];
      if (touch.identifier === touchId) {
        resetJoystick();
        touchId = null;
        break;
      }
    }
  });
}

// 更新摇杆位置
function updateJoystickPosition(touchX, touchY) {
  const joystickHandle = document.getElementById('joystickHandle');
  
  const deltaX = touchX - joystickBaseX;
  const deltaY = touchY - joystickBaseY;
  
  const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
  
  let limitedX = deltaX;
  let limitedY = deltaY;
  
  if (distance > joystickBaseRadius) {
    limitedX = (deltaX / distance) * joystickBaseRadius;
    limitedY = (deltaY / distance) * joystickBaseRadius;
  }
  
  joystickHandle.style.transform = `translate(calc(-50% + ${limitedX}px), calc(-50% + ${limitedY}px))`;
  
  const angle = Math.atan2(limitedY, limitedX) * 180 / Math.PI;
  
  let newDirection = null;
  
  if (distance > 15) {
    if (angle >= -45 && angle < 45) {
      newDirection = 'right';
    } else if (angle >= 45 && angle < 135) {
      newDirection = 'down';
    } else if (angle >= 135 || angle < -135) {
      newDirection = 'left';
    } else {
      newDirection = 'up';
    }
  }
  
  if (newDirection !== currentJoystickDirection) {
    currentJoystickDirection = newDirection;
    if (newDirection) {
      changeDirection(newDirection);
    }
  }
}

// 重置摇杆
function resetJoystick() {
  const joystickHandle = document.getElementById('joystickHandle');
  joystickHandle.style.transform = 'translate(-50%, -50%)';
  joystickHandle.classList.remove('active');
  isJoystickActive = false;
  currentJoystickDirection = null;
}

// 手势控制
function setupGestureControls() {
  const gestureArea = document.getElementById('gestureArea');
  let startX, startY;
  
  gestureArea.addEventListener('touchstart', function(e) {
    e.preventDefault();
    const touch = e.touches[0];
    startX = touch.clientX;
    startY = touch.clientY;
  });
  
  gestureArea.addEventListener('touchmove', function(e) {
    e.preventDefault();
  });
  
  gestureArea.addEventListener('touchend', function(e) {
    e.preventDefault();
    const touch = e.changedTouches[0];
    const endX = touch.clientX;
    const endY = touch.clientY;
    
    const dx = endX - startX;
    const dy = endY - startY;
    
    if (Math.abs(dx) > 20 || Math.abs(dy) > 20) {
      if (Math.abs(dx) > Math.abs(dy)) {
        if (dx > 0) {
          changeDirection('right');
        } else {
          changeDirection('left');
        }
      } else {
        if (dy > 0) {
          changeDirection('down');
        } else {
          changeDirection('up');
        }
      }
    }
  });
}

// 虚拟方向键控制
function setupVirtualControls() {
  const directionBtns = document.querySelectorAll('.direction-btn[data-direction]');
  
  directionBtns.forEach(btn => {
    btn.addEventListener('touchstart', function(e) {
      e.preventDefault();
      const direction = this.dataset.direction;
      changeDirection(direction);
      this.style.background = 'rgba(255, 215, 0, 0.6)';
    });
    
    btn.addEventListener('touchend', function(e) {
      e.preventDefault();
      this.style.background = 'rgba(255, 255, 255, 0.2)';
    });
    
    btn.addEventListener('touchmove', function(e) {
      e.preventDefault();
    });
  });
}

// 改变方向
function changeDirection(direction) {
  const directions = {
    'up': { x: 0, y: -1 },
    'down': { x: 0, y: 1 },
    'left': { x: -1, y: 0 },
    'right': { x: 1, y: 0 }
  };
  
  const newDir = directions[direction];
  if (newDir) {
    if (!(dir.x === -newDir.x && dir.y === -newDir.y)) {
      dir = newDir;
    }
  }
}

// 重新开始游戏
function restartGame() {
  if (gameLoopId) {
    cancelAnimationFrame(gameLoopId);
    gameLoopId = null;
  }
  
  document.getElementById('gameOver').style.display = 'none';
  totalPoints = 0;
  currentLevel = 0;
  init();
}

// 排行榜功能
function getRankings() {
  return JSON.parse(localStorage.getItem('snakeRankings') || '[]');
}

function saveRanking(playerName, score, difficulty) {
  const rankings = getRankings();
  const newRecord = {
    name: playerName,
    score: score,
    difficulty: difficulty,
    date: new Date().toLocaleDateString()
  };
  
  rankings.push(newRecord);
  rankings.sort((a, b) => b.score - a.score);
  const topRankings = rankings.slice(0, 10);
  
  localStorage.setItem('snakeRankings', JSON.stringify(topRankings));
  return rankings.findIndex(record => record === newRecord) + 1;
}

function showRanking() {
  const finalScore = +document.getElementById('finalPoints').textContent;
  const rank = saveRanking(currentPlayer, finalScore, currentDifficulty);
  
  const rankings = getRankings();
  const rankingList = document.getElementById('rankingList');
  rankingList.innerHTML = '';
  
  rankings.forEach((record, index) => {
    const rankingItem = document.createElement('div');
    rankingItem.className = `ranking-item ${record.name === currentPlayer && record.score === finalScore ? 'current' : ''}`;
    
    rankingItem.innerHTML = `
      <div>
        <span class="rank-number">${index + 1}.</span>
        <span class="player-name">${record.name}</span>
        <small style="color: #aaa; margin-left: 10px;">${record.difficulty}</small>
      </div>
      <div class="player-score">${record.score}分</div>
    `;
    
    rankingList.appendChild(rankingItem);
  });
  
  document.getElementById('gameScreen').style.display = 'none';
  document.getElementById('rankingScreen').style.display = 'flex';
}

function playAgain() {
  document.getElementById('rankingScreen').style.display = 'none';
  document.getElementById('gameScreen').style.display = 'block';
  totalPoints = 0;
  currentLevel = 0;
  init();
}

function backToMenu() {
  if (gameLoopId) {
    cancelAnimationFrame(gameLoopId);
    gameLoopId = null;
  }
  
  document.getElementById('rankingScreen').style.display = 'none';
  document.getElementById('gameScreen').style.display = 'none';
  document.getElementById('startScreen').style.display = 'flex';
  totalPoints = 0;
  currentLevel = 0;
}

/* ====== 游戏核心代码 ====== */
const LEVELS = [
  { 
    score: 0,
    walls: [],
    speedMultiplier: 1.0,
    tips: "熟悉操作，收集食物，避开炸弹！",
    difficulty: "简单",
    wallStyle: "simple"
  },
  { 
    score: 20,
    walls: [
      {x:10,y:14,w:6,h:1},
      {x:16,y:8,w:4,h:1}
    ],
    speedMultiplier: 1.1,
    tips: "注意避开障碍物和炸弹",
    difficulty: "简单+",
    wallStyle: "brick"
  },
  { 
    score: 45,
    walls: [
      {x:8,y:12,w:5,h:1},
      {x:18,y:18,w:5,h:1},
      {x:5,y:5,w:3,h:1}
    ],
    speedMultiplier: 1.25,
    tips: "障碍物增多，炸弹出现更频繁",
    difficulty: "中等",
    wallStyle: "metal"
  },
  { 
    score: 75,
    walls: [
      {x:6,y:10,w:4,h:1},
      {x:16,y:10,w:4,h:1},
      {x:6,y:20,w:4,h:1},
      {x:16,y:20,w:4,h:1},
      {x:12,y:15,w:2,h:1}
    ],
    speedMultiplier: 1.4,
    tips: "复杂地形，小心炸弹",
    difficulty: "困难",
    wallStyle: "crystal"
  },
  { 
    score: 110,
    walls: [
      {x:4,y:8,w:3,h:1},
      {x:15,y:8,w:3,h:1},
      {x:4,y:18,w:3,h:1},
      {x:15,y:18,w:3,h:1},
      {x:10,y:13,w:4,h:1},
      {x:8,y:15,w:1,h:3}
    ],
    speedMultiplier: 1.6,
    tips: "终极挑战！到处都是危险",
    difficulty: "专家",
    wallStyle: "lava"
  }
];

const FOOD_TYPES = {
  APPLE: {
    name: "苹果",
    score: 1,
    color: "#0af",
    glowColor: "#0af",
    probability: 0.6,
    effect: "normal",
    lifetime: 15000,
    warningTime: 5000
  },
  STRAWBERRY: {
    name: "草莓",
    score: 2,
    color: "#ff4081",
    glowColor: "#ff4081",
    probability: 0.25,
    effect: "bonus",
    lifetime: 12000,
    warningTime: 4000
  },
  CAKE: {
    name: "蛋糕",
    score: 5,
    color: "#ffd700",
    glowColor: "#ffd700",
    probability: 0.1,
    effect: "special",
    lifetime: 8000,
    warningTime: 3000
  },
  BOMB: {
    name: "炸弹",
    score: 0,
    color: "#ff4444",
    glowColor: "#ff4444",
    probability: 0.05,
    effect: "deadly",
    lifetime: 20000,
    warningTime: 8000
  }
};

const DEF = {
  cell: 20,
  size: '480*640'
};

function setCanvasSize(s) {
  const [w, h] = s.split('*').map(Number);
  canvas.width = w; canvas.height = h;
  W = w / DEF.cell; H = h / DEF.cell;
}
setCanvasSize(DEF.size);

function init() {
  const config = DIFFICULTY_CONFIG[currentDifficulty];
  baseSpeed = config.speed;
  
  snake = [{x: W >> 1, y: H >> 1}];
  dir = {x: 1, y: 0};
  score = 0;
  particles = []; 
  foods = [];
  lastMove = performance.now(); 
  isLevelTransitioning = false;
  
  for (let i = 0; i < 3; i++) {
    createFood();
  }
  
  // 设置控制
  if (currentControlMode === 'virtual') {
    setupVirtualControls();
  }
  
  document.getElementById('score').textContent = score;
  document.getElementById('points').textContent = totalPoints;
  document.getElementById('highScore').textContent = highScore;
  document.getElementById('gameOver').style.display = 'none';
  document.getElementById('newRecord').style.display = 'none';
  document.getElementById('level').textContent = currentLevel + 1;
  document.getElementById('difficultyText').textContent = config.name;
  document.getElementById('levelTransition').style.display = 'none';
  
  gameLoopId = requestAnimationFrame(loop);
}

function getRandomFoodType() {
  const config = DIFFICULTY_CONFIG[currentDifficulty];
  const rand = Math.random();
  let cumulative = 0;
  
  const adjustedProbabilities = {...FOOD_TYPES};
  adjustedProbabilities.BOMB.probability = config.bombRate;
  
  const otherFoodsTotalProb = 1 - adjustedProbabilities.BOMB.probability;
  const scaleFactor = otherFoodsTotalProb / (FOOD_TYPES.APPLE.probability + FOOD_TYPES.STRAWBERRY.probability + FOOD_TYPES.CAKE.probability);
  
  adjustedProbabilities.APPLE.probability = FOOD_TYPES.APPLE.probability * scaleFactor;
  adjustedProbabilities.STRAWBERRY.probability = FOOD_TYPES.STRAWBERRY.probability * scaleFactor;
  adjustedProbabilities.CAKE.probability = FOOD_TYPES.CAKE.probability * scaleFactor;
  
  const foodTypes = [adjustedProbabilities.APPLE, adjustedProbabilities.STRAWBERRY, adjustedProbabilities.CAKE, adjustedProbabilities.BOMB];
  
  for (const foodType of foodTypes) {
    cumulative += foodType.probability;
    if (rand <= cumulative) {
      return foodType;
    }
  }
  return adjustedProbabilities.APPLE;
}

function canCreateBomb() {
  const config = DIFFICULTY_CONFIG[currentDifficulty];
  const currentBombs = foods.filter(food => food.type.effect === "deadly").length;
  return currentBombs < config.maxBombs;
}

function createFood() {
  let p;
  let attempts = 0;
  const maxAttempts = 50;
  
  do {
    p = {x: Math.floor(Math.random() * W), y: Math.floor(Math.random() * H)};
    attempts++;
    if (attempts > maxAttempts) break;
  } while (
    snake.some(s => s.x === p.x && s.y === p.y) ||
    foods.some(f => f.x === p.x && f.y === p.y) ||
    LEVELS[currentLevel].walls.some(w => inWall(p.x, p.y, w))
  );
  
  if (attempts <= maxAttempts) {
    let foodType = getRandomFoodType();
    
    if (foodType.effect === "deadly" && !canCreateBomb()) {
      foodType = FOOD_TYPES.APPLE;
    }
    
    foods.push({
      x: p.x,
      y: p.y,
      type: foodType,
      createTime: Date.now(),
      life: 1.0
    });
  }
}

function updateFoodLifetimes() {
  const now = Date.now();
  for (let i = foods.length - 1; i >= 0; i--) {
    const food = foods[i];
    const elapsed = now - food.createTime;
    const remainingTime = food.type.lifetime - elapsed;
    
    if (remainingTime <= 0) {
      createDisappearEffect(food.x, food.y, food.type.color);
      foods.splice(i, 1);
      createFood();
    } else {
      food.life = remainingTime / food.type.lifetime;
      if (remainingTime <= food.type.warningTime) {
        food.warning = true;
      }
    }
  }
}

function createDisappearEffect(cx, cy, color) {
  for (let i = 0; i < 8; i++) {
    const ang = Math.random() * Math.PI * 2, spd = Math.random() * 2 + 1;
    particles.push({ 
      x: (cx + 0.5) * DEF.cell, 
      y: (cy + 0.5) * DEF.cell, 
      vx: Math.cos(ang) * spd, 
      vy: Math.sin(ang) * spd, 
      r: Math.random() * 2 + 1, 
      life: 0.6, 
      color, 
      textMode: false 
    });
  }
}

function inWall(x, y, w) {
  return x >= w.x && x < w.x + w.w && y >= w.y && y < w.y + w.h;
}

function loop(t) {
  if (isLevelTransitioning) {
    gameLoopId = requestAnimationFrame(loop);
    return;
  }
  
  const currentSpeed = baseSpeed / LEVELS[currentLevel].speedMultiplier;
  if (t - lastMove > currentSpeed) { 
    lastMove = t; 
    update(); 
  }
  draw(t);
  gameLoopId = requestAnimationFrame(loop);
}

function update() {
  const head = {x: snake[0].x + dir.x, y: snake[0].y + dir.y};
  
  if (head.x < 0 || head.x >= W || head.y < 0 || head.y >= H || 
      snake.some(s => s.x === head.x && s.y === head.y) ||
      LEVELS[currentLevel].walls.some(w => inWall(head.x, head.y, w))) {
    gameOver();
    return;
  }
  
  snake.unshift(head);
  let ateFood = false;
  
  for (let i = foods.length - 1; i >= 0; i--) {
    const food = foods[i];
    if (head.x === food.x && head.y === food.y) {
      if (food.type.effect === "deadly") {
        bombExplosion(head.x, head.y);
        flashRed();
        navigator.vibrate && navigator.vibrate(200);
        gameOver();
        return;
      } else {
        const points = food.type.score;
        score += points;
        totalPoints += points;
        updatePoints();
        floatText(head.x, head.y, `+${points}`, food.type.color);
        
        if (food.type.effect === "special") {
          specialExplosion(head.x, head.y, food.type.color);
          flashGold();
          navigator.vibrate && navigator.vibrate(100);
        } else if (food.type.effect === "bonus") {
          bonusExplosion(head.x, head.y, food.type.color);
        }
        
        foods.splice(i, 1);
        createFood();
        ateFood = true;
        break;
      }
    }
  }
  
  if (!ateFood) {
    snake.pop();
  }
  
  updateFoodLifetimes();
  
  if (foods.length < 3) {
    createFood();
  }
  
  if (currentLevel < LEVELS.length - 1 && score >= LEVELS[currentLevel + 1].score) {
    startLevelTransition();
  }
}

function startLevelTransition() {
  isLevelTransitioning = true;
  transitionCountdown = 3;
  document.getElementById('nextLevelNum').textContent = currentLevel + 2;
  document.getElementById('levelTransition').style.display = 'flex';
  document.getElementById('countdown').textContent = transitionCountdown;
  
  const countdownInterval = setInterval(() => {
    transitionCountdown--;
    document.getElementById('countdown').textContent = transitionCountdown;
    
    if (transitionCountdown <= 0) {
      clearInterval(countdownInterval);
      nextLevel();
    }
  }, 1000);
}

function nextLevel() {
  currentLevel++;
  document.getElementById('levelTransition').style.display = 'none';
  document.getElementById('difficultyText').textContent = DIFFICULTY_CONFIG[currentDifficulty].name;
  init();
}

function draw(t) {
  ctx.fillStyle = '#111'; 
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  drawWalls();
  
  foods.forEach(food => {
    drawFood(food);
  });
  
  snake.forEach((p, i) => {
    const size = DEF.cell * (1 - i / snake.length * 0.25);
    const colorValue = Math.max(100, 255 - i * 2);
    ctx.fillStyle = i === 0 ? '#0f0' : `rgba(0,${colorValue},120,0.7)`;
    roundRect((p.x + 0.5) * DEF.cell - size / 2, (p.y + 0.5) * DEF.cell - size / 2, size, size, size * 0.2); 
    ctx.fill();
  });
  
  const h = snake[0], cs = DEF.cell;
  ctx.fillStyle = '#000';
  const ex = h.x * cs + cs * 0.3, ey = h.y * cs + cs * 0.25, ew = cs * 0.1, eh = cs * 0.25;
  ctx.fillRect(ex, ey, ew, eh); 
  ctx.fillRect(ex + cs * 0.3, ey, ew, eh);
  
  particles = particles.filter(p => {
    if (p.textMode) { 
      ctx.font = 'bold 16px Arial'; 
      ctx.fillStyle = p.color; 
      ctx.fillText(p.text, p.x, p.y); 
      p.y -= 1.2; 
    } else { 
      p.x += p.vx; 
      p.y += p.vy; 
      p.life -= 0.02; 
      ctx.globalAlpha = p.life; 
      ctx.fillStyle = p.color; 
      ctx.fillRect(p.x, p.y, p.r, p.r); 
      ctx.globalAlpha = 1; 
    }
    return p.life > 0;
  });
}

function drawWalls() {
  const wallStyle = LEVELS[currentLevel].wallStyle;
  const walls = LEVELS[currentLevel].walls;
  
  walls.forEach(wall => {
    const x = wall.x * DEF.cell;
    const y = wall.y * DEF.cell;
    const width = wall.w * DEF.cell;
    const height = wall.h * DEF.cell;
    
    switch (wallStyle) {
      case "brick":
        ctx.fillStyle = '#8B4513';
        ctx.fillRect(x, y, width, height);
        ctx.strokeStyle = '#A0522D';
        ctx.lineWidth = 1;
        for (let i = 0; i < wall.w; i++) {
          for (let j = 0; j < wall.h; j++) {
            ctx.strokeRect(x + i * DEF.cell, y + j * DEF.cell, DEF.cell, DEF.cell);
          }
        }
        break;
      case "metal":
        const gradient = ctx.createLinearGradient(x, y, x + width, y + height);
        gradient.addColorStop(0, '#7F7F7F');
        gradient.addColorStop(0.5, '#BFBFBF');
        gradient.addColorStop(1, '#7F7F7F');
        ctx.fillStyle = gradient;
        ctx.fillRect(x, y, width, height);
        break;
      case "crystal":
        ctx.fillStyle = 'rgba(100, 200, 255, 0.6)';
        ctx.fillRect(x, y, width, height);
        break;
      case "lava":
        const lavaGradient = ctx.createLinearGradient(x, y, x, y + height);
        lavaGradient.addColorStop(0, '#FF4500');
        lavaGradient.addColorStop(0.5, '#FF6347');
        lavaGradient.addColorStop(1, '#DC143C');
        ctx.fillStyle = lavaGradient;
        ctx.fillRect(x, y, width, height);
        break;
      default:
        ctx.fillStyle = '#666';
        ctx.fillRect(x, y, width, height);
        break;
    }
  });
}

function drawFood(food) {
  const pulse = 1 + 0.1 * Math.sin(Date.now() * 0.005 + food.x);
  let size = DEF.cell * 0.38 * pulse;
  
  if (food.warning) {
    const blink = Math.sin(Date.now() * 0.02) > 0;
    if (blink) {
      ctx.globalAlpha = 0.6;
    }
    size *= 0.8;
  }
  
  ctx.shadowBlur = 15;
  ctx.shadowColor = food.type.glowColor;
  ctx.fillStyle = food.type.color;
  
  if (food.type.effect === "deadly") {
    const blink = Math.sin(Date.now() * 0.01) > 0;
    if (blink || food.warning) {
      ctx.beginPath();
      ctx.arc((food.x + 0.5) * DEF.cell, (food.y + 0.5) * DEF.cell, size, 0, Math.PI * 2);
      ctx.fill();
    }
  } else {
    ctx.beginPath();
    ctx.arc((food.x + 0.5) * DEF.cell, (food.y + 0.5) * DEF.cell, size, 0, Math.PI * 2);
    ctx.fill();
  }
  
  ctx.shadowBlur = 0;
  ctx.globalAlpha = 1;
}

function floatText(cx, cy, text, color) {
  particles.push({ 
    x: (cx + 0.5) * DEF.cell, 
    y: (cy + 0.5) * DEF.cell, 
    text, color, life: 1, textMode: true 
  });
}

function specialExplosion(cx, cy, color) {
  for (let i = 0; i < 30; i++) {
    const ang = Math.random() * Math.PI * 2, spd = Math.random() * 4 + 2;
    particles.push({ 
      x: (cx + 0.5) * DEF.cell, 
      y: (cy + 0.5) * DEF.cell, 
      vx: Math.cos(ang) * spd, 
      vy: Math.sin(ang) * spd, 
      r: Math.random() * 4 + 2, 
      life: 1, 
      color, 
      textMode: false 
    });
  }
}

function bonusExplosion(cx, cy, color) {
  for (let i = 0; i < 15; i++) {
    const ang = Math.random() * Math.PI * 2, spd = Math.random() * 3 + 1;
    particles.push({ 
      x: (cx + 0.5) * DEF.cell, 
      y: (cy + 0.5) * DEF.cell, 
      vx: Math.cos(ang) * spd, 
      vy: Math.sin(ang) * spd, 
      r: Math.random() * 2 + 1, 
      life: 0.8, 
      color, 
      textMode: false 
    });
  }
}

function bombExplosion(cx, cy) {
  for (let i = 0; i < 50; i++) {
    const ang = Math.random() * Math.PI * 2, spd = Math.random() * 6 + 3;
    particles.push({ 
      x: (cx + 0.5) * DEF.cell, 
      y: (cy + 0.5) * DEF.cell, 
      vx: Math.cos(ang) * spd, 
      vy: Math.sin(ang) * spd, 
      r: Math.random() * 3 + 1, 
      life: 1, 
      color: i % 2 === 0 ? '#ff4444' : '#ff8844', 
      textMode: false 
    });
  }
}

function flashGold() {
  ctx.fillStyle = 'rgba(255,221,0,0.3)'; 
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  setTimeout(() => ctx.clearRect(0, 0, canvas.width, canvas.height), 100);
}

function flashRed() {
  ctx.fillStyle = 'rgba(255,0,0,0.4)'; 
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  setTimeout(() => ctx.clearRect(0, 0, canvas.width, canvas.height), 150);
}

function roundRect(x, y, w, h, r) {
  ctx.beginPath(); 
  ctx.moveTo(x + r, y); 
  ctx.arcTo(x + w, y, x + w, y + h, r); 
  ctx.arcTo(x + w, y + h, x, y + h, r); 
  ctx.arcTo(x, y + h, x, y, r); 
  ctx.arcTo(x, y, x + w, y, r); 
  ctx.closePath();
}

function updatePoints() {
  document.getElementById('score').textContent = score;
  document.getElementById('points').textContent = totalPoints;
  
  if (totalPoints > highScore) {
    highScore = totalPoints;
    localStorage.setItem('snakeHighScore', highScore);
    document.getElementById('highScore').textContent = highScore;
  }
}

function gameOver() {
  if (gameLoopId) {
    cancelAnimationFrame(gameLoopId);
    gameLoopId = null;
  }
  
  const final = totalPoints;
  document.getElementById('finalPoints').textContent = final;
  
  const levelProgress = `到达第 ${currentLevel + 1} 关`;
  document.getElementById('finalTxt').innerHTML = `游戏结束！${levelProgress}`;
  
  if (final > highScore) {
    highScore = final;
    localStorage.setItem('snakeHighScore', highScore);
    document.getElementById('highScore').textContent = highScore;
    document.getElementById('newRecord').style.display = 'block';
  } else if (highScore > 0) {
    document.getElementById('finalTxt').innerHTML += `<br>距纪录差 <b>${highScore - final}</b> 分`;
  }
  
  document.getElementById('gameOver').style.display = 'block';
}

// 键盘控制
document.addEventListener('keydown', e => {
  const D = { 
    ArrowUp: { x: 0, y: -1 }, 
    ArrowDown: { x: 0, y: 1 }, 
    ArrowLeft: { x: -1, y: 0 }, 
    ArrowRight: { x: 1, y: 0 },
    'w': { x: 0, y: -1 },
    's': { x: 0, y: 1 },
    'a': { x: -1, y: 0 },
    'd': { x: 1, y: 0 }
  };
  
  if (D[e.key]) { 
    const nd = D[e.key];
    if (dir.x + nd.x !== 0 || dir.y + nd.y !== 0) {
      if (!(dir.x === -nd.x && dir.y === -nd.y)) {
        dir = nd;
      }
    }
  }
});

// 页面加载
window.addEventListener('load', function() {
  document.getElementById('playerName').focus();
  highScore = localStorage.getItem('snakeHighScore') || 0;
  document.getElementById('highScore').textContent = highScore;
  
  const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
  if (isMobile) {
    document.body.style.touchAction = 'none';
  }
});
</script>
</body>
</html>